#!/usr/bin/perl

use warnings;
use strict;
use Regexp::Common 'balanced';

my $file = shift;
open my $in, $file or die "can't open $file: $!\n";
my $sgf = do { local $/; <$in> };
close $in or die "can't close $file: $!\n";

my @sgf;
while ($sgf =~ /$RE{balanced}{-parens=>'()'}{-keep}/g) {
    push @sgf => $1;
}

$file =~ s/\.sgf$//;
mkdir $file or die "can't mkdir $file: $!\n";

# Construct a format string used for numbering individual sgf files. The
# format depends on how many problems there are in the collection. If there
# are between 10 and 99 problems, we want the individual files to be named
# "foo/foo-01.sgf" and so on. If there are 100 problems or more, we want
# "foo/foo-001.sgf".

my $format = sprintf "%s/%s-%%0%sd.sgf", $file, $file, 1+int(log(@sgf)/log(10));
my $cnt;
for (@sgf) {
    my $name = sprintf $format => ++$cnt;
    open my $out, ">$name" or die "can't open $name for writing: $!\n";
    print $out $_;
    close $out or die "can't close $out: $!\n";
}
